package pers.qianyu.month_202101.date_20210118;

/**
 * 208. 实现 Trie (前缀树)
 * https://leetcode-cn.com/problems/implement-trie-prefix-tree/
 *
 * @author mizzle rain
 * @date 2021年1月18日15:23:27
 */
public class Trie {
    private static class Node {
        Node[] links;
        private final int R = 26;
        private boolean isEnd;

        public Node() {
            links = new Node[R];
        }

        private boolean containsKey(char ch) {
            return links[ch - 'a'] != null;
        }

        public Node get(char ch) {
            return links[ch - 'a'];
        }

        public void put(char ch, Node node) {
            links[ch - 'a'] = node;
        }

        public boolean isEnd() {
            return isEnd;
        }

        public void setEnd(boolean end) {
            isEnd = end;
        }
    }

    private Node root;

    /**
     * Initialize your data structure here.
     */
    public Trie() {
        root = new Node();
    }

    /**
     * Inserts a word into the trie.
     */
    public void insert(String word) {
        Node p = root;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            if (!p.containsKey(ch)) {
                p.put(ch, new Node());
            }
            p = p.get(ch);
        }
        p.setEnd(true);
    }

    /**
     * Returns if the word is in the trie.
     */
    public boolean search(String word) {
        Node p = searchPrefix(word);
        return p != null && p.isEnd();
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }

    private Node searchPrefix(String prefix) {
        Node p = root;
        for (int i = 0; i < prefix.length(); i++) {
            char ch = prefix.charAt(i);
            if (p.containsKey(ch)) {
                p = p.get(ch);
            } else {
                return null;
            }
        }
        return p;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */